package com.moli.iov.down.command.design.decorator.dectrators;

import com.moli.iov.down.constants.Constant;
import com.moli.iov.down.enums.command.CommandEnum;
import com.moli.iov.down.model.dto.remoting.CommandDto;
import com.moli.iov.down.command.design.decorator.AbstractDecorator;
import com.moli.iov.down.command.design.decorator.AbstractSendCommand;
import com.moli.iov.down.command.mq.activemq.ActiveMqProducer;
import com.moli.iov.util.ByteUtils;
import com.moli.iov.util.SpringContextUtils;
import com.moli.iov.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 *  发送ActiveMQ 延时消息
 * </p>
 *
 * @author: zql
 * @Date: 2018/12/28 14:33
 */
@Slf4j
public class ActiveMqDecorator extends AbstractDecorator {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public ActiveMqDecorator(AbstractSendCommand aSendCommand) {
        super(aSendCommand);
    }

    @Override
    public void sendCommand(CommandDto commandDto, byte[] allData) {
        try{
            sendCommandBiz(commandDto, allData);
        }catch (Exception e){
            log.error("下发命令 发送ActiveMQ 延时消息 异常", e);
        }
        super.sendCommand(commandDto, allData);
    }

    /**
     * 延时消息
     * @param commandDto
     * @param allData
     */
    public void sendCommandBiz(CommandDto commandDto, byte[] allData){

        String commandStr = StringUtil.bytesToHexString(commandDto.getCommand());
        String data = ByteUtils.bytesToHexString(allData);
        String msg = commandDto.getIsRetry() == null || !commandDto.getIsRetry() ? "不需要补发命令" : "补发命令";
        logger.info("[下行报文] {} IsRetry: null, vin：{}, command：{}, 数据：{}" ,
                msg, commandDto.getVin(), commandStr, data);

        if(commandDto.getIsRetry() == null && !commandDto.getIsRetry()){
            return;
        }

        commandDto.setSendingTimes(commandDto.getSendingTimes() == null ? 0 : commandDto.getSendingTimes() + 1);

        ActiveMqProducer activeMQProducer = SpringContextUtils.getBean("activeMQProducer");
        activeMQProducer.send(commandDto, getDelayTime(commandDto.getCommand()));
    }

    /**
     * 获取 延时时长
     * @param command
     * @return
     */
    public Long getDelayTime(Byte command){

        if(CommandEnum.REMOTE_UPGRADE.getFlag() == command){

            return Constant.UPGRADE_INTERVAL_DELAY_TIME;
        }
        return Constant.GENERAL_DELAY_TIME;
    }
}
